package com.baizhi.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.baizhi.entity.DdUser;
import com.baizhi.service.impl.DdUserServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author xutengyang
 * @since 2020-12-14
 */
@RestController
public class DdUserController {
    @Autowired
    private DdUserServiceImpl dsi;


    //验证码(放行请求)
    @GetMapping("verifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 10);
        //将验证码放入session
        session.setAttribute("captcha",captcha);
        //写出到浏览器
        captcha.write(response.getOutputStream());
    }
    //判断验证码是否正确:异步请求判断
    @GetMapping("captcha")
    public Map verifyCaptcha(String userCode, HttpServletRequest request){
        System.out.println(userCode);
        HttpSession session = request.getSession();
        CircleCaptcha captcha = (CircleCaptcha) session.getAttribute("captcha");
        System.out.println(captcha.getCode());
        boolean equals = captcha.verify(userCode);
        if (equals){
            return new HashMap(){{
                put("code","successful");
            }};
        }else {
            return new HashMap(){{
                put("code","failed");
            }};
        }
    }
    //登陆
    @GetMapping("users")
    public Map login(DdUser user,HttpServletRequest request){
        HttpSession session = request.getSession();
        //释放session中的验证码
        session.removeAttribute("captcha");
        System.out.println("用户输入的信息为："+user);
        QueryWrapper<DdUser> wrapper = new QueryWrapper<>();
        wrapper
                .eq("email ",user.getEmail())
                .eq("password",user.getPassword());
        DdUser user2 = dsi.getOne(wrapper);
        if (user2!=null){
            session.setAttribute("user",user2);
            return new HashMap(){{
                put("code","successful");
            }};
        }else {
            return new HashMap(){{
                put("code","failed");
                put("message","用户不存在或密码错误");
            }};
        }
    }

}

